package com.person.jc.service.security;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.person.jc.entity.TsUser;
import com.person.jc.service.Service;
import com.person.jc.utils.MyMD5;
import com.person.jc.utils.Utils;

public class TsUserService extends Service {
	
	public static final TsUserService me = new TsUserService();
	
	public TsUser getUserById(String userId){
		TsUser tsUser = null;
		Record rd =  Db.findFirst("select t.*,t1.dept_name from ts_user t , ts_dept t1 where t.dept_id = t1.dept_id and t.status = 1 and t.user_id = ?", userId);
		if(rd != null){
			tsUser = new TsUser();
			tsUser.setUserId(rd.getStr("user_id"));
			tsUser.setUserName(rd.getStr("user_name"));
			tsUser.setPassword(rd.getStr("password"));
			tsUser.setStatus(String.valueOf(rd.getInt("status")));
			tsUser.setDeptId(rd.getStr("dept_id"));
			tsUser.setDeptName(rd.getStr("dept_name"));
			tsUser.setRankId(String.valueOf(rd.getInt("rank_id")));
			tsUser.setSex(String.valueOf(rd.getInt("sex")));
			tsUser.setLinkPhone(rd.getStr("link_phone"));
			tsUser.setIdCard(rd.getStr("id_card"));
			tsUser.setEmergencyUser(rd.getStr("emergency_user"));
			tsUser.setEmergencyContact(rd.getStr("emergency_contact"));
			tsUser.setEmergencyRel(rd.getStr("emergency_rel"));
		}
		return tsUser;
	}
	
	public List<Record> getList(Map<String,Object> map){
		String temp = "";
		List<Object> params = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer("select t.user_id,\n" +
				"       t.password,\n" + 
				"       t.user_name,\n" + 
				"       t.rank_id,\n" + 
				"       t.link_phone,\n" + 
				"       t.sex,\n" + 
				"       t.dept_id,\n" + 
				"       t.id_card,\n" + 
				"       t.emergency_user,\n" + 
				"       t.emergency_contact,\n" + 
				"       t.emergency_rel,\n" + 
				"       t2.dept_name,\n" + 
				"       t4.kind_name sex_name,\n" + 
				"       t5.rank_name,\n" + 
				"       t.status\n" + 
				"  from ts_user t\n" + 
				"  join ts_dept t2 on t.dept_id = t2.dept_id\n" + 
				"  left join ts_code_kind_data t4 on t.sex = t4.kind_code and t4.type_code = 'sex'\n" + 
				"  left join ts_code_rank t5 on t.rank_id = t5.rank_id"+
				" where t.status <> 3");
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("userId")))){
			sql.append(" and t.user_id like ?");
			params.add("%"+temp+"%");
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("deptId")))){
			sql.append(" and t.dept_id like ?");
			params.add(""+temp+"%");
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("userName")))){
			sql.append(" and t.user_name like ?");
			params.add("%"+temp+"%");
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("status")))){
			sql.append(" and t.status = ?");
			params.add(temp);
		}
		sql.append(" order by t.dept_id, t.user_id");
		return Db.find(sql.toString(), Utils.getObjParam(params));
	}
	
	public void save(Map<String,Object> map){
		List<Object> params = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into ts_user(user_id,user_name,password,status,dept_id,sex,link_phone,id_card,emergency_user,emergency_contact,emergency_rel)");
		sql.append(" values(?,?,?,?,?,?,?,?,?,?,?)");
		params.add(map.get("userId"));
		params.add(map.get("userName"));
		params.add(MyMD5.myMD5(String.valueOf(map.get("password"))));
		params.add(map.get("status"));
		params.add(map.get("deptId"));
		params.add(map.get("sex"));
		params.add(map.get("linkPhone"));
		params.add(map.get("idCard"));
		params.add(map.get("emergencyUser"));
		params.add(map.get("emergencyContact"));
		params.add(map.get("emergencyRel"));
		Db.update(sql.toString(), Utils.getObjParam(params));
		super.setCRUD("用户管理", "C", "新增用户信息："+map.get("userId"));
	}
	
	public void update(Map<String,Object> map){
		List<Object> params = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" update ts_user set");
		sql.append(" user_name = ? ,");
		sql.append(" password = ? ,");
		sql.append(" status = ? ,");
		sql.append(" dept_id = ? ,");
		sql.append(" sex = ? ,");
		sql.append(" id_card = ? ,");
		sql.append(" emergency_user = ? ,");
		sql.append(" emergency_contact = ? ,");
		sql.append(" emergency_rel = ? ,");
		sql.append(" link_phone = ?");
		sql.append(" where user_id = ?");
		params.add(map.get("userName"));
		params.add(map.get("password"));
		params.add(map.get("status"));
		params.add(map.get("deptId"));
		params.add(map.get("sex"));
		params.add(map.get("idCard"));
		params.add(map.get("emergencyUser"));
		params.add(map.get("emergencyContact"));
		params.add(map.get("emergencyRel"));
		params.add(map.get("linkPhone"));
		params.add(map.get("userId"));
		Db.update(sql.toString(), Utils.getObjParam(params));
		super.setCRUD("用户管理", "U", "修改用户信息："+map.get("userId"));
	}
	
	public void updateStatus(String ids ,String status){
		String[] id = ids.split(",");
		Object[][] paras = new Object[id.length][2];
		for (int i = 0; i < id.length; i++) {
			paras[i][0] = status;
			paras[i][1] = id[i];
		}
		String sql = " update ts_user set status = ? where user_id = ?";
		Db.batch(sql, paras, id.length);
		super.setCRUD("用户管理", "U", "更改用户状态:"+ids+"("+status+")");
	}
	
	public long getNameCount(String userId){
		String sql = "select count(1) from ts_user where user_id = ?";
		return Db.queryLong(sql, userId);
	}
	
	public void delUserRole(String userId) {
		String sql = "delete from ts_user_role_vcl where user_id = ? ";
		Db.update(sql, new Object[]{ userId});
		super.setCRUD("用户管理", "D", "删除用户角色信息:"+userId);
	}

	public void saveUserRole(Map<String, Object> map) {
		final String userId = String.valueOf(map.get("userId"));
		final String[] roleIds;
		if(map.get("roleId") instanceof String){
		    roleIds = new String[]{String.valueOf(map.get("roleId"))};
		}else{
		    roleIds = (String [])(map.get("roleId"));
		}
		if(null!=roleIds){
			Object[][] paras = new Object[roleIds.length][2];
			for (int i = 0; i < roleIds.length; i++) {
				paras[i][0] = roleIds[i];
				paras[i][1] = userId;
			}
			String sql = " insert into ts_user_role_vcl(role_id,user_id) values ( ?, ?)";
			Db.batch(sql, paras, roleIds.length);
			super.setCRUD("角色管理", "C", "新增用户角色信息:"+userId);
			
		}
	}
	
	public void updatePw(String userId, String newPassword) {
        String sql = "update ts_user set password = ?  where user_id = ?";
        Db.update(sql, newPassword,userId);
	}
}
